import type { MockMethod } from 'vite-plugin-mock';

// Mock用户数据
const mockUsers = [
  {
    id: '1',
    username: 'admin',
    password: 'admin123',
    name: '系统管理员',
    phone: '13800138000',
    email: 'admin@example.com',
  },
  {
    id: '2',
    username: 'test',
    password: 'test123',
    name: '测试用户',
    phone: '13900139000',
    email: 'test@example.com',
  },
];

// 临时存储验证码的Map
const verifyCodes = new Map<string, { code: string; expireTime: number }>();

// Mock数据配置
const userMock: MockMethod[] = [
  // 登录接口
  {
    url: '/api/auth/login',
    method: 'post',
    response: (config: any) => {
      const { username, password } = config.body;
      const user = mockUsers.find(u => u.username === username && u.password === password);
      
      if (user) {
        return {
          success: true,
          data: {
            token: `token_${user.id}_${Date.now()}`,
            user: {
              id: user.id,
              username: user.username,
              name: user.name,
            },
          },
          message: '登录成功',
        };
      }
      
      return {
        success: false,
        message: '用户名或密码错误',
        code: 401,
      };
    },
  },
  
  // 获取用户信息接口
  {
    url: '/api/auth/user/info',
    method: 'get',
    response: (config: any) => {
      // 从请求头获取token
      const token = config.headers?.['Authorization']?.replace('Bearer ', '');
      
      if (token) {
        // 从token中提取用户ID（简单模拟）
        const userId = token.split('_')[1];
        const user = mockUsers.find(u => u.id === userId);
        
        if (user) {
          return {
            success: true,
            data: {
              id: user.id,
              username: user.username,
              name: user.name,
            },
          };
        }
      }
      
      return {
        success: false,
        message: '未授权',
        code: 401,
      };
    },
  },
  
  // 登出接口
  {
    url: '/api/auth/logout',
    method: 'post',
    response: () => {
      return {
        success: true,
        message: '登出成功',
      };
    },
  },
  
  // 发送验证码接口
  {
    url: '/api/auth/send-code',
    method: 'post',
    response: (config: any) => {
      const { account, type } = config.body;
      
      // 查找是否有匹配的用户
      const user = mockUsers.find(u => 
        (type === 'phone' && u.phone === account) || 
        (type === 'email' && u.email === account)
      );
      
      if (!user) {
        return {
          success: false,
          message: '账号不存在',
          code: 404,
        };
      }
      
      // 生成验证码（模拟）
      const code = Math.floor(100000 + Math.random() * 900000).toString();
      const expireTime = Date.now() + 5 * 60 * 1000; // 5分钟过期
      
      // 存储验证码
      const key = `${type}_${account}`;
      verifyCodes.set(key, { code, expireTime });
      console.log(code)
      // 开发环境打印验证码便于测试
      console.log(`验证码已发送至 ${type === 'phone' ? '手机' : '邮箱'} ${account}，验证码：${code}`);
      
      return {
        success: true,
        data: {
          expireIn: 300, // 5分钟
          message: '验证码发送成功',
        },
        message: '验证码发送成功',
      };
    },
  },
  
  // 验证码登录接口
  {
    url: '/api/auth/login-by-code',
    method: 'post',
    response: (config: any) => {
      const { account, code, type } = config.body;
      
      // 查找用户
      const user = mockUsers.find(u => 
        (type === 'phone' && u.phone === account) || 
        (type === 'email' && u.email === account)
      );
      
      if (!user) {
        return {
          success: false,
          message: '账号不存在',
          code: 404,
        };
      }
      
      // 验证验证码
      const key = `${type}_${account}`;
      const stored = verifyCodes.get(key);
      
      if (!stored) {
        return {
          success: false,
          message: '验证码不存在或已过期',
          code: 400,
        };
      }
      
      if (stored.expireTime < Date.now()) {
        verifyCodes.delete(key);
        return {
          success: false,
          message: '验证码已过期',
          code: 400,
        };
      }
      
      if (stored.code !== code) {
        return {
          success: false,
          message: '验证码错误',
          code: 400,
        };
      }
      
      // 验证码验证成功，清除验证码
      verifyCodes.delete(key);
      
      return {
        success: true,
        data: {
          token: `token_${user.id}_${Date.now()}`,
          user: {
            id: user.id,
            username: user.username,
            name: user.name,
          },
        },
        message: '登录成功',
      };
    },
  },
];

export default userMock;